package com.david.core.utils

import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity

/**
 * 获取所有文件权限
 * 1.manifest中声明权限(targetVersion大于等于30时)：<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
 * 2.动态获取权限，获取之后执行对应操作
 */
fun requestAllFilePermission(activity: AppCompatActivity, permissionResult: ((ActivityResult) -> Unit)? = null) {
    val startForResult = activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        permissionResult?.invoke(result)
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        startForResult.launch(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
    } else {
        startForResult.launch(Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS))
    }
}